using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WegasManagementSystem.BLL;
using WegasManagementSystem.Models;

namespace WegasManagementSystem.Forms
{
    public partial class SalaryCalculatorForm : Form
    {
        private DepartmentBLL _departmentBLL;
        private EmployeeBLL _employeeBLL;
        private SalaryBLL _salaryBLL;
        private List<Employee> _employees;

        public SalaryCalculatorForm()
        {
            InitializeComponent();
            _departmentBLL = new DepartmentBLL();
            _employeeBLL = new EmployeeBLL();
            _salaryBLL = new SalaryBLL();
        }

        private void SalaryCalculatorForm_Load(object sender, EventArgs e)
        {
            // 初始化年月选择器为当前月份
            dtpYearMonth.Value = DateTime.Now;
            lblYearMonth.Text = $"当前计算：{dtpYearMonth.Value.ToString("yyyy-MM")}";

            // 加载部门列表
            LoadDepartments();

            // 加载员工列表
            LoadEmployees();
        }

        private void LoadDepartments()
        {
            try
            {
                List<Department> departments = _departmentBLL.GetAllDepartments();
                
                // 添加"全部部门"选项
                Department allDept = new Department
                {
                    DeptId = 0,
                    DeptName = "全部部门"
                };
                departments.Insert(0, allDept);

                cboDepartment.DataSource = departments;
                cboDepartment.DisplayMember = "DeptName";
                cboDepartment.ValueMember = "DeptId";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载部门列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadEmployees()
        {
            try
            {
                int deptId = cboDepartment.SelectedValue != null ? Convert.ToInt32(cboDepartment.SelectedValue) : 0;
                
                if (deptId == 0)
                {
                    // 获取所有员工
                    _employees = _employeeBLL.GetAllEmployees();
                }
                else
                {
                    // 获取选定部门的员工
                    _employees = _employeeBLL.GetEmployeesByDepartment(deptId);
                }

                // 设置DataGridView数据源
                dgvEmployees.DataSource = _employees.Select(e => new
                {
                    员工ID = e.EmpId,
                    员工编号 = e.EmpNumber,
                    员工姓名 = e.EmpName,
                    所属部门 = e.DeptName,
                    职位 = e.Position,
                    入职日期 = e.HireDate,
                    状态 = e.Status == 1 ? "在职" : "离职"
                }).ToList();

                // 隐藏计算结果面板
                groupResult.Visible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载员工列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cboDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadEmployees();
        }

        private void dtpYearMonth_ValueChanged(object sender, EventArgs e)
        {
            lblYearMonth.Text = $"当前计算：{dtpYearMonth.Value.ToString("yyyy-MM")}";
            // 隐藏计算结果面板
            groupResult.Visible = false;
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            if (dgvEmployees.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要计算工资的员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                // 获取选中员工ID
                int empId = Convert.ToInt32(dgvEmployees.SelectedRows[0].Cells["员工ID"].Value);
                // 获取选中年月
                DateTime yearMonth = dtpYearMonth.Value;
                
                // 计算员工工资
                SalaryInfo salaryInfo = _salaryBLL.CalculateSalary(empId, yearMonth.Year, yearMonth.Month);

                // 显示计算结果
                DisplaySalaryResult(salaryInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"计算工资失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnBatchCalculate_Click(object sender, EventArgs e)
        {
            if (_employees == null || _employees.Count == 0)
            {
                MessageBox.Show("没有可计算工资的员工", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                // 获取选中年月
                DateTime yearMonth = dtpYearMonth.Value;
                int year = yearMonth.Year;
                int month = yearMonth.Month;
                
                // 获取部门ID
                int deptId = cboDepartment.SelectedValue != null ? Convert.ToInt32(cboDepartment.SelectedValue) : 0;

                // 确认批量计算
                DialogResult result = MessageBox.Show(
                    $"确定要为{(deptId == 0 ? "所有" : cboDepartment.Text)}员工计算{year}年{month}月工资吗？",
                    "确认批量计算",
                    MessageBoxButtons.YesNo, 
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 批量计算工资
                    int count = _salaryBLL.BatchCalculateSalary(deptId, year, month);
                    MessageBox.Show($"批量计算完成，共计算{count}名员工的工资", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量计算工资失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            // 已移除Excel导出功能
            MessageBox.Show("Excel导出功能已禁用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void DisplaySalaryResult(SalaryInfo salaryInfo)
        {
            // 显示计算结果面板
            groupResult.Visible = true;

            // 设置基本信息
            lblEmpName.Text = "员工姓名：" + salaryInfo.EmpName;
            lblDeptName.Text = "所属部门：" + salaryInfo.DeptName;
            
            // 更新年月信息
            if (lblYearMonth != null)
                lblYearMonth.Text = salaryInfo.Year + "-" + salaryInfo.Month.ToString("00");
            
            // 设置工资各项 - 使用标签字段或构建动态内容
            lblTotalIncome.Text = "总收入：¥" + salaryInfo.TotalIncome.ToString("0.00");
            lblTotalDeduction.Text = "总扣款：¥" + salaryInfo.TotalDeduction.ToString("0.00");
            lblNetSalary.Text = "实发工资：¥" + salaryInfo.NetSalary.ToString("0.00");
            
            // 创建工资详情文本（替代缺失的标签）
            string details = $"基本工资: {salaryInfo.BaseSalary:0.00}\n" +
                           $"岗位津贴: {salaryInfo.PositionAllowance:0.00}\n" +
                           $"绩效奖金: {salaryInfo.PerformanceBonus:0.00}\n" +
                           $"加班工资: {salaryInfo.OvertimePay:0.00}\n" +
                           $"社保: {salaryInfo.SocialInsurance:0.00}\n" +
                           $"公积金: {salaryInfo.HousingFund:0.00}\n" +
                           $"个税: {salaryInfo.IncomeTax:0.00}\n" +
                           $"缺勤扣款: {salaryInfo.AbsenceDeduction:0.00}\n" +
                           $"其他扣款: {salaryInfo.OtherDeductions:0.00}";
                           
            // 考虑在UI中显示或者使用其他控件显示详情
            MessageBox.Show(details, "工资详情", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
} 